/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Bartosz Michalik (bartosz.michalik@gmail.com)
 *******************************************************************************/
package org.eclipse.pde.internal.ui.editor.product;

import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.*;
import org.eclipse.pde.core.IModelChangedEvent;
import org.eclipse.pde.core.IModelChangedListener;
import org.eclipse.pde.core.plugin.*;
import org.eclipse.pde.internal.core.*;
import org.eclipse.pde.internal.core.iproduct.*;
import org.eclipse.pde.internal.core.product.ProductTransformFactory;
import org.eclipse.pde.internal.ui.editor.PDEFormPage;
import org.eclipse.pde.internal.ui.editor.TreeSection;
import org.eclipse.pde.internal.ui.editor.plugin.ExtensionContentProvider;
import org.eclipse.pde.internal.ui.editor.product.customization.RemoveFeatureAction;
import org.eclipse.pde.internal.ui.editor.product.customization.RemoveTransformAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

/**
 * First customization section - merely asks if you wish to use customizations.
 */
public class ExtensionCustomizationSection extends TreeSection {

	private class RefreshListener implements IModelChangedListener, IExtensionDeltaListener, IPluginModelListener {

		private TreeViewer fViewer;

		/**
		 * 
		 */
		public RefreshListener(TreeViewer viewer) {
			this.fViewer = viewer;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.core.IModelChangedListener#modelChanged(org.eclipse.pde.core.IModelChangedEvent)
		 */
		public void modelChanged(IModelChangedEvent event) {
			if (IModelChangedEvent.WORLD_CHANGED == event.getChangeType()) {
				refresh();
				return;
			}
			Object[] changedObjects = event.getChangedObjects();
			boolean needsUpdating = false;
			for (int i = 0; i < changedObjects.length; ++i) {
				if (changedObjects[i] instanceof IProductTransform) {
					refreshObject((IProductTransform) changedObjects[i]);
				} else {
					needsUpdating = true;
					break;
				}
			}
			if (needsUpdating)
				refresh();
		}

		private void refreshObject(IProductTransform object) {
			IPluginObject transformed = (IPluginObject) object.getTransformedObject();
			List toUpdate = new LinkedList();
			while (transformed != null) {
				toUpdate.add(transformed);
				transformed = transformed.getParent();
			}
			transformed = (IPluginObject) object.getTransformedObject();
			fViewer.update(toUpdate.toArray(), null);
			fViewer.refresh(transformed, true);
			fViewer.setSelection(new StructuredSelection(transformed), true);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.internal.core.IExtensionDeltaListener#extensionsChanged(org.eclipse.pde.internal.core.IExtensionDeltaEvent)
		 */
		public void extensionsChanged(IExtensionDeltaEvent event) {
			refresh();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.internal.core.IPluginModelListener#modelsChanged(org.eclipse.pde.internal.core.PluginModelDelta)
		 */
		public void modelsChanged(PluginModelDelta delta) {
			refresh();
		}

		/**
		 * TODO optimize
		 */
		private void refresh() {
			IProductModel productModel = getProductModel();
			if (productModel == null)
				return;
			fViewer.setInput(productModel.getProduct());
			fViewer.refresh();
		}

	}

	private RefreshListener fRefreshListener;
	private ExtensionCustomizationLabelProvider fLabelProvider;
	private TreeViewer fTreeViewer;

	/**
	 * @param page
	 * @param parent
	 * @param style
	 */
	public ExtensionCustomizationSection(PDEFormPage page, Composite parent) {
		super(page, parent, Section.DESCRIPTION, new String[] {"Restore To Configuration", "Remove From Configuration"});
		//		createClient(getSection(), page.getEditor().getToolkit());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.pde.internal.ui.editor.PDESection#createClient(org.eclipse.ui.forms.widgets.Section,
	 *      org.eclipse.ui.forms.widgets.FormToolkit)
	 */
	protected void createClient(Section section, FormToolkit toolkit) {
		section.setText("Extensions");
		GridData sectionData = new GridData(GridData.FILL_BOTH);
		sectionData.horizontalSpan = 2;
		sectionData.verticalSpan = 3;
		section.setLayoutData(sectionData);
		Composite container = createClientContainer(section, 3, toolkit);
		createViewerPartControl(container, SWT.MULTI, 3, toolkit);
		fTreeViewer = getTreePart().getTreeViewer();
		fTreeViewer.setContentProvider(new ExtensionContentProvider());
		fLabelProvider = new ExtensionCustomizationLabelProvider(getCustomizationInfo(), toolkit);
		fTreeViewer.setLabelProvider(fLabelProvider);
		fTreeViewer.setInput((getProductModel()).getProduct());
		fTreeViewer.setComparer(new IElementComparer() {

			public boolean equals(Object a, Object b) {
				if (a.equals(b))
					return true;
				if (a instanceof IPluginObject && b instanceof IPluginObject) {
					String xp1 = ProductTransformFactory.toXPath(a, true);
					String xp2 = ProductTransformFactory.toXPath(b, true);
					return xp1.equals(xp2);
				}
				return false;
			}

			public int hashCode(Object element) {
				return element.hashCode();
			}

		});

		toolkit.paintBordersFor(container);
		section.setClient(container);
		fRefreshListener = new RefreshListener(fTreeViewer);

		PDECore.getDefault().getModelManager().addExtensionDeltaListener(fRefreshListener);
		PDECore.getDefault().getModelManager().addPluginModelListener(fRefreshListener);
		getProductModel().addModelChangedListener(fRefreshListener);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.AbstractFormPart#dispose()
	 */
	public void dispose() {
		getProductModel().removeModelChangedListener(fRefreshListener);
		PDECore.getDefault().getModelManager().removeExtensionDeltaListener(fRefreshListener);
		PDECore.getDefault().getModelManager().removePluginModelListener(fRefreshListener);
		super.dispose();
	}

	/**
	 * The customization info for this product.
	 * 
	 * @return the info
	 */
	protected ICustomizationInfo getCustomizationInfo() {
		ICustomizationInfo customizationInfo = (getProductModel()).getProduct().getCustomizationInfo();
		if (customizationInfo == null) {
			IProductModel productModel = getProductModel();
			customizationInfo = productModel.getFactory().createCustomizationInfo();
			productModel.getProduct().setCustomizationInfo(customizationInfo);
		}
		return customizationInfo;
	}

	/**
	 * Add actions that do the magic 
	 */
	protected void fillContextMenu(IMenuManager manager) {
		// LOOK_HERE create menu
		ITransformationsManager transformsManager = getCustomizationInfo().getTransformsManager();
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
		if (!selection.isEmpty()) {
			Object element = selection.getFirstElement();
			if (element instanceof IPluginElement || element instanceof IPluginExtension) {
				if (transformsManager.isAffected((IPluginObject) element)) {
					if (transformsManager.isTransformed((IPluginObject) element)) {
						manager.add(new RemoveTransformAction(getCustomizationInfo(), selection));
					}
				} else {
					manager.add(new RemoveFeatureAction(getCustomizationInfo(), selection));
				}
			}
		}
	}

	/**
	 * @return
	 */
	private IProductModel getProductModel() {
		return (IProductModel) getPage().getPDEEditor().getAggregateModel();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.pde.internal.ui.editor.StructuredViewerSection#buttonSelected(int)
	 */
	protected void buttonSelected(int index) {
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
		if (index == 0) {
			new RemoveTransformAction(getCustomizationInfo(), selection).run();
		} else {
			new RemoveFeatureAction(getCustomizationInfo(), selection).run();
		}
	}

	protected void enableButtons() {
		// TODO Auto-generated method stub
		super.enableButtons();
	}

}
